package group.sicher.lock.component.impl;

import group.sicher.lock.component.MarsLockInterfaceAbstractor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @description:
 * @author: aron
 * @date: 2019-08-05 15:44
 */
public class MarsReentrantLockInterfaceComponent extends MarsLockInterfaceAbstractor {

    @Qualifier("marsLockClient")
    @Autowired
    private RedissonClient lockRedissonClient;

    private RLock lock;


    @Override
    public void lock() throws Exception {
        this.lock = lockRedissonClient.getLock(marsLockKey.getKeyList().get(0));

        if (marsLockKey.getLeaseTime() == -1 && marsLockKey.getWaitTime() == -1) {
            lock.lock();
            return;
        }
        if (marsLockKey.getLeaseTime() != -1 && marsLockKey.getWaitTime() == -1) {
            lock.lock(marsLockKey.getLeaseTime(), marsLockKey.getTimeUnit());
            return;
        }
        if (marsLockKey.getLeaseTime() != -1 && marsLockKey.getWaitTime() != -1) {
            lock.tryLock(marsLockKey.getWaitTime(), marsLockKey.getLeaseTime(), marsLockKey.getTimeUnit());
            return;
        }

        lock.lock();
    }

    @Override
    public void close() {
        lock.unlock();
    }
}
